import axios from 'axios';
// 引入UI提示组件
import { ElMessage } from 'element-plus';
// eslint-disable-next-line no-unused-vars
import router from '../router';

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    // 在发送请求之前做某事
    config.headers['agentId'] = process.env.VUE_APP_agentId;
    if (sessionStorage.getItem('token')) {
      config.headers['DF-User-Token'] = sessionStorage.getItem('token'); // 让每个请求携带token--['DF-User-Token']为自定义key 请根据实际情况自行修改
    }
    if (sessionStorage.getItem('language')) {
      config.headers['Accept-Language'] = sessionStorage.getItem('language');
    }
    return config;
  },
  error => {
    // 请求错误时做些事
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(
  function(response) {
    // 对响应数据做点什么
    return response.data;
  },
  function(error) {
    // 对响应错误做点什么
    console.log(error.message);
    return Promise.reject(error);
  }
);

function successState(res) {
  // 统一判断后端返回的错误码
  if (res.code == 0) {
    ElMessage.error(res.message);
  }
  if (res.code == 10000) {
    // Message.error('登陆失效，请重新登录')
    router.push({
      path: '/'
    });
  }
  if (res.code == 401) {
    ElMessage.error('无访问权限');
  }
}

function errorState(response) {
  console.log(response.message);
  ElMessage.error('网络异常');
}

const httpServer = (opts, data) => {
  let Public = {
    // 公共参数
    // 'user': "guzhenxing"
  };
  let obj = {
    url: opts.url,
    method: opts.method
  };
  let headers = {
    'X-Requested-With': 'XMLHttpRequest',
    Accept: 'application/json',
    'Content-Type': 'application/json; charset=UTF-8'
  };
  let method = opts.method.toLowerCase();
  if (method == 'get') {
    headers = {
      'X-Requested-With': 'XMLHttpRequest',
      Accept: 'application/json',
      'Content-Type': 'application/json; charset=UTF-8'
    };
  } else if (method == 'post') {
    headers = {
      'X-Requested-With': 'XMLHttpRequest',
      Accept: 'application/json',
      // 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
      'Content-Type': 'application/json; charset=UTF-8'
    };
  } else if (method == 'delete') {
    obj.url = obj.url + data.id;
    data = {};
  }

  let httpDefaultOpts = {
    // http默认配置
    method: obj.method,
    baseURL: '',
    url: obj.url,
    timeout: 600000,
    params: Object.assign(Public, data),
    data: data,
    headers: headers
  };

  if (method == 'get') {
    delete httpDefaultOpts.data;
  } else if (method == 'post') {
    delete httpDefaultOpts.params;
  } else {
    delete httpDefaultOpts.data;
  }

  let promise = new Promise(function(resolve, reject) {
    axios(httpDefaultOpts)
      .then(res => {
        successState(res);
        resolve(res);
      })
      .catch(response => {
        errorState(response);
        reject(response);
      });
  });
  return promise;
};

export default httpServer;
